<?php

namespace yunj\app\admin\validate\member;

use yunj\app\admin\enum\State;
use yunj\app\admin\enum\TableBuilderEvent;
use yunj\app\admin\service\auth\AuthService;
use yunj\app\admin\validate\Validate;

class MemberRoleValidate extends Validate {

    protected function handleData(array &$data, $scene): void {
        switch ($scene) {
            case 'RoleListEvent':
                $this->handleDataByRoleListEvent($data);
                break;
            case 'RoleFormSubmit':
                $this->handleDataByRoleFormSubmit($data);
                break;
        }
    }

    private function handleDataByRoleListEvent(&$data): void {
        $event = $data['event'];
        $ids = $data['ids'];
        // 系统定义拥有所有权限的角色不可移入回收站或者删除
        if ($event == TableBuilderEvent::DELETED || $event == TableBuilderEvent::RECYLE_BIN) {
            /** @var TableBuilderEvent $eventObj */
            $eventObj = TableBuilderEvent::byValue($event);
            $hasAllAuthRoleAliasArr = self::getAdminMemberRoleModel()->getColumnOptions('alias', [
                ['id', 'in', $ids],
                ['alias', 'in', AuthService::HAS_ALL_AUTH_ROLES],
            ]);
            if ($hasAllAuthRoleAliasArr) {
                throw_error_json('系统定义拥有所有权限的角色[' . implode('、', $hasAllAuthRoleAliasArr) . ']不可' . $eventObj->getDesc());
            }
        }
    }

    private function handleDataByRoleFormSubmit(&$data): void {
        $id = $data['id'] ?? 0;

        $currTime = time();
        $dbRoleData = [
            'name' => $data['name'],
            'intro' => $data['intro'],
            'last_update_time' => $currTime,
        ];

        if ($id) {
            // 编辑
            // 判断数据是否存在
            $roleData = self::getAdminMemberRoleModel()->getOwnRowToArray([
                ['id', '=', $id],
                ['state', '<>', State::DELETED]
            ]);
            if (!$roleData) throw_error_json('数据异常，请刷新页面后重试');
            $data['rawRoleData'] = $roleData;
            $dbRoleData['id'] = $id;
        } else {
            // 添加
            $dbRoleData += [
                'create_time' => $currTime,
            ];
        }

        // alias 别名
        $newAlias = '';
        if (isset($data['alias'])) {
            $alias = $data['alias'];
            if ($roleData = $data['rawRoleData'] ?? []) {
                // 拥有所有权限的角色别名不能编辑
                if (in_array($roleData['alias'], AuthService::HAS_ALL_AUTH_ROLES, true) && $alias !== $roleData['alias']) {
                    throw_error_json('角色[' . $roleData['alias'] . ']别名不允许编辑');
                }
            }

            // 是否存在
            $where = [
                ['alias', '=', $alias]
            ];
            if ($id) $where[] = ['id', '<>', $id];
            $hasExist = self::getAdminMemberRoleModel()->getOwnCount($where);
            if ($hasExist) throw_error_json('角色别名[' . $alias . ']已存在');
            $dbRoleData['alias'] = $newAlias = $alias;
        }

        // auths
        if (!in_array($newAlias, AuthService::HAS_ALL_AUTH_ROLES, true)) {
            // top_auths 顶部菜单权限配置
            if ($topAuths = $data['top_auths'] ?? []) $auths = array_merge($auths ?? [], $topAuths);
            // sidebar_auths 侧边栏权限配置
            if ($sidebarAuths = $data['sidebar_auths'] ?? []) $auths = array_merge($auths ?? [], $sidebarAuths);
            // other_auths 其他权限配置
            if ($otherAuths = $data['other_auths'] ?? []) $auths = array_merge($auths ?? [], $otherAuths);
            if (isset($auths)) {
                $dbRoleData['auths'] = json_encode(array_unique($auths));
            }
        }
        $data['dbRoleData'] = $dbRoleData;
    }

}